<?php


	import("persistence.database.ResultSet");
	import("persistence.database.Query");
	class DataBase {
		var $__DBOBJECT__;
		var $__connectionURI__;
		
		function connect($URIObject=NULL){
			if($URIObject==NULL){
				import("net.URI");
				$URIObject = new URI(DB_DEFAULT);
			}
			switch(strtolower($URIObject->protocol)){
				case "mysql":
					$db_type = "MySQL";
					break;
			}
			import("persistence.database.sql.".$db_type);
			$this->__DBOBJECT__ = new $db_type();
			return $this->__DBOBJECT__->connect($URIObject);
		}
		
		function selectDB($dbName){
			$select = $this->__DBOBJECT__->selectDB($dbName);
		}
		
		function &query($query){
			if(strToLower(get_class($query))=="query"){
				$queryString = $query->build();
			}else{
				$queryString = $query;
			}
			if(APP_DEBUG_MODE){
				import("error.Logger");
				Logger::log("DataBase",$queryString);
			}
			$this->__DBOBJECT__->query($queryString,$query->__processfounds__);
			$resultSet =& $this->createResultSet();
			/*echo "[".$query->__processfounds__."] ";*/
			if($query->__processfounds__){
				$resultSet->setTotal($this->__DBOBJECT__->total);
			}
			return $resultSet;
		}
		
		function execute($queryString){
			if(strToLower(get_class($queryString))=="query"){
				$queryString = $queryString->build();
			}
			if(APP_DEBUG_MODE) Logger::log("DataBase",$queryString);
			$status = $this->__DBOBJECT__->query($queryString);
			if(!$status) die($this->__DBOBJECT__->error());
			return $status;
		}
		
        function getLastId() {
            return $this->__DBOBJECT__->getLastID();
        }
        
		function &createResultSet(){
			$resultData = array();
			while($this->__DBOBJECT__->rowsLoop()){
				$dt = $this->__DBOBJECT__->getRow();
				if(!isset($rowFields)) $rowFields = array_keys($dt);
			    $resultData[] = $dt;
			}
			if(count($resultData)>0){
				$rs = new ResultSet($resultData);
				$rs->setFields($rowFields);
			}else{
				$rs = NULL;
			}
			return $rs;
		}
		
		function run($query){
			$db = new DataBase();
			$db->connect();
			$res = $db->query($query);
			return $res;
		}
	}
?>
